package us.codecraft.webmagic.processor.example;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.ConsolePipeline;
import us.codecraft.webmagic.processor.PageProcessor;

/**
 * @author code4crafter@gmail.com <br>
 * @since 0.6.0
 */
public class ZhihuPageProcessorExtension implements PageProcessor {

    private Site site = Site.me().setRetryTimes(3).setSleepTime(1000);

    public static void main(String[] args) {
        Spider.create(new ZhihuPageProcessorExtension())
                //此处用于将process处理结果通过pipeline管道输出出来
                .addPipeline(new ConsolePipeline())
                .addUrl("https://www.zhihu.com/explore").run();
    }

    /****
     *
     * text() 用于直接获取元素节点内的文字内容(不包括子节点的内容)
     * tidyText()  用于获取所有子元素节点下的内容
     * @param page page
     */
    @Override
    public void process(Page page) {
        page.addTargetRequests(page.getHtml().links().regex("https://www\\.zhihu\\.com/question/\\d+/answer/\\d+.*").all());
        page.putField("title", page.getHtml().xpath("//*[@id=\"guestSquare\"]/div[2]/div/div[2]/div[1]/div/text()").toString());
        page.putField("question", page.getHtml().xpath("//*[@id=\"guestSquare\"]/div[2]/div/div[2]/div[2]/div//tidyText()").toString());
        if (page.getResultItems().get("title") == null) {
            //skip this page
            page.setSkip(true);
        }
    }

    @Override
    public Site getSite() {
        return site;
    }
}
